package com.xhorse.lockplatform.service.impl;

import com.xhorse.lockplatform.comm.constant.ConstantString;
import com.xhorse.lockplatform.comm.constant.FilePathDefine;
import com.xhorse.lockplatform.comm.enums.ResultEnum;
import com.xhorse.lockplatform.comm.exception.LockPlatFormException;
import com.xhorse.lockplatform.comm.model.BaseMessage;
import com.xhorse.lockplatform.comm.service.BaseService;
import com.xhorse.lockplatform.comm.util.FileTransport;
import com.xhorse.lockplatform.comm.util.HttpClientUtil;
import com.xhorse.lockplatform.comm.util.Paginator;
import com.xhorse.lockplatform.dao.mapper.XhAppUpdateInfoMapper;
import com.xhorse.lockplatform.model.XhAppUpdateInfo;
import com.xhorse.lockplatform.service.AppUpdateInfoService;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AppUpdateInfoServiceImpl extends BaseService<XhAppUpdateInfo> implements AppUpdateInfoService {

    @Autowired
    private XhAppUpdateInfoMapper xhAppUpdateInfoMapper;

    /**
     * 获取更新信息
     */
    @Override
    public Map<String, Object> getUpdateInfo(String build, int type,
                                             int languageId) {
        BaseMessage baseMessage = new BaseMessage();
        XhAppUpdateInfo xhAppUpdateInfo = new XhAppUpdateInfo();
        int builder = Integer.valueOf(build);
        List<Integer> forcbilityList = xhAppUpdateInfoMapper.getVersionList(
                builder, type, languageId);

        if (forcbilityList.isEmpty()) {
            xhAppUpdateInfo.setBuild(builder); // 若为空，则表明是已是最新版本，返回当前版本号即可
        } else {
            xhAppUpdateInfo = xhAppUpdateInfoMapper.getLatestVersionInfo(
                    builder, type, languageId);
            if (xhAppUpdateInfo.getType() == 2) { // 若type==2，表明是安卓端，则还要提供下载的rul
                baseMessage.baseMsg
                        .put("downloadURL", "AppVersion/apkDownload");
            }
            if (forcbilityList.contains(1)) { // 若版本列表存在强制更新，则设置最新版本必须强制更新
                xhAppUpdateInfo.setForcibility(1);
            }
        }
        baseMessage.putStatus(ResultEnum.SUCCESS.getCode());
        baseMessage.putData(xhAppUpdateInfo);
        return baseMessage.baseMsg;
    }

    /**
     * 将提交的版本信息进行处理
     */
    @Override
    public void updateInfo(XhAppUpdateInfo xhAppUpdateInfo) {
        XhAppUpdateInfo obj = xhAppUpdateInfoMapper.getLatestVersionInfo(xhAppUpdateInfo.getBuild(),
                xhAppUpdateInfo.getType(), xhAppUpdateInfo.getLanguageId());
        if (obj == null) {
            xhAppUpdateInfoMapper.insertSelective(xhAppUpdateInfo);
        } else {
            xhAppUpdateInfoMapper.updateByPrimaryKeySelective(xhAppUpdateInfo);
        }
    }

    @Override
    public List<XhAppUpdateInfo> getAppInfoList(int type) {
        return xhAppUpdateInfoMapper.selectByType(type);
    }

    @Override
    public int deleteUpdateInfo(int id) {
        String fileLocation = FilePathDefine.APK_DOWNLOAD_PATH
                + xhAppUpdateInfoMapper.selectByPrimaryKey(id).getFileName();
        FileTransport ft = new FileTransport();
        ft.deleteFile(fileLocation);
        return xhAppUpdateInfoMapper.deleteById(id);
    }

    @Override
    public Map<String, String> getLatestAppDeviceVer(
            HttpServletRequest request, int type, int regionId) {
        try {
            RequestBody requestBody = new FormBody.Builder()
                    .add("regionId", regionId + "").add("cmd", "24").build();
            HttpClientUtil httpClientUtil = HttpClientUtil.getInstance();
            String verToken = request.getHeader("verToken");
            if (verToken == null) {
                verToken = httpClientUtil.verTokenGenerate(ConstantString.USERNAME);
            }
            Request myrequest = new Request.Builder()
                    .url(ConstantString.PHP_URL_DATATRANSFER)
                    .addHeader("verToken", verToken).post(requestBody).build();
            Response response = httpClientUtil.getClient().newCall(myrequest)
                    .execute();
            String deviceVersion = response.body().string();
            if (deviceVersion.equals("-1") || deviceVersion.equals("-2")
                    || deviceVersion.equals("-3") || deviceVersion.equals("-4")) {
                return null;
            }
            Map<String, String> result = new HashMap<String, String>();
            String appVersion = xhAppUpdateInfoMapper
                    .selectMaxVersionByType(type);
            result.put("appVersion", appVersion);
            result.put("deviceVersion", deviceVersion);
            return result;
        } catch (Exception e) {
            throw new LockPlatFormException(ResultEnum.FAILED.getCode(), "版本接口[getLatestAppDeviceVer]，遇到异常", e);
        }
    }

    @Override
    public List<XhAppUpdateInfo> selectByParam(Paginator page) {
        return xhAppUpdateInfoMapper.select(page);
    }

}
